package v2.structure.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 基于cglib-3.3.0.jar和asm-7.1.jar实现，cglib依赖于asm实现
 *
 * 提供Cglib抽象代理类，通过子类来实现对业务类方法增强，在方法前和方法后提供逻辑
 *
 * @author : zhenyun.su
 * @since : 2023/10/12
 */

public abstract class BaseCglibProxy  {

    private Object target;

    public BaseCglibProxy(Object target) {
        this.target = target;
    }

    public Object getProxyObject(){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.target.getClass());
        enhancer.setCallback(new MethodInterceptor(){
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                before(target, objects, method.getName());
                Object result = methodProxy.invoke(target, objects);
                after(target, objects, method.getName(), result);
                return result;
            }
        });
        return enhancer.create();
    }

    public abstract void before(Object target, Object[] args, String methodNme);

    public abstract void after(Object target, Object[] args, String methodNme, Object result);

}
